import * as API from './api'

/**
 * 订阅消息工具类
 * 处理微信小程序订阅消息相关功能
 */
const SubscribeMessage = {
  /**
   * 显示订阅邀请弹窗
   * @param {string} templateId - 订阅消息模板ID
   * @param {Function} successCallback - 订阅成功回调
   */
  showSubscribeMessage(templateId, successCallback) {
    uni.showModal({
      title: "邀请",
      content: "我们正式邀请您成为我们的订阅嘉宾，获取最新消息",
      success: (res) => {
        if (res.confirm) {
          this.subscribeMessage(templateId, successCallback);
        }
      }
    });
  },

  /**
   * 处理订阅逻辑
   * @param {string} templateId - 订阅消息模板ID
   * @param {Function} successCallback - 订阅成功回调
   */
  subscribeMessage(templateId, successCallback) {
    let openid = uni.getStorageSync('openid');
    if (openid) {
      this.postMessage(templateId, successCallback);
    } else {
      this.getOpenid(templateId, successCallback);
    }
  },

  /**
   * 请求订阅消息
   * @param {string} templateId - 订阅消息模板ID
   * @param {Function} successCallback - 订阅成功回调
   */
  postMessage(templateId, successCallback) {
    let openid = uni.getStorageSync('openid');
    uni.requestSubscribeMessage({
      tmplIds: [templateId],
      success: res => {
        const templateStatus = res[templateId];
        if (templateStatus === 'accept') {
          this.notifyBackend(openid, templateId, true, successCallback);
        } else {
          uni.showToast({
            title: '订阅状态异常: ' + templateStatus,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '订阅请求失败',
          icon: 'none'
        });
        console.error('订阅请求失败:', err);
      }
    });
  },

  /**
   * 通知后端订阅状态
   * @param {string} openid - 用户openid
   * @param {string} templateId - 订阅消息模板ID
   * @param {boolean} isSubscribe - 是否订阅
   * @param {Function} successCallback - 成功回调
   */
  notifyBackend(openid, templateId, isSubscribe, successCallback) {
    const apiUrl = isSubscribe ? API.postSubscribe : API.postUnsubscribe;
    let data = {
      openid: openid,
      template_id: templateId
    };

    apiUrl(data).then((res) => {
      if (res.data.success) {
        const statusMessage = isSubscribe ? '订阅成功！' : '取消订阅成功';
        uni.showToast({
          title: statusMessage,
          icon: 'none'
        });
        if (successCallback && typeof successCallback === 'function') {
          successCallback();
        }
      } else {
        uni.showToast({
          title: '操作失败: ' + (res.data.message || '未知错误'),
          icon: 'none'
        });
      }
    }).catch((err) => {
      uni.showToast({
        title: '接口请求失败',
        icon: 'none'
      });
      console.error('订阅接口请求失败:', err);
    });
  },

  /**
   * 获取用户openid并继续订阅流程
   * @param {string} templateId - 订阅消息模板ID
   * @param {Function} successCallback - 订阅成功回调
   */
  getOpenid(templateId, successCallback) {
    uni.login({
      provider: 'weixin',
      success: (loginRes) => {
        API.postOpenid({ code: loginRes.code }).then((res) => {
          if (res.statusCode === 200 && res.data.openid) {
            uni.setStorageSync('openid', res.data.openid);
            uni.showModal({
              title: "提示",
              content: "感谢您愿意成为我们的订阅嘉宾",
              showCancel: false,
              success: () => {
                this.postMessage(templateId, successCallback);
              }
            });
          } else {
            uni.showToast({
              title: '获取OpenID失败',
              icon: 'none'
            });
          }
        }).catch((err) => {
          uni.showToast({
            title: '获取OpenID接口失败',
            icon: 'none'
          });
          console.error('获取OpenID失败:', err);
        });
      },
      fail: (err) => {
        uni.showToast({
          title: '登录失败',
          icon: 'none'
        });
        console.error('登录失败:', err);
      }
    });
  }
};

export default SubscribeMessage;